<?php
require 'vendor/autoload.php'; // 引入自动加载文件
require 'enum.php';

use enums\Color;
use annotate\NoReturn;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$index = new Index();
$index->read();

class Index {
    public function read(): void {
        $directory = 'E:\xlsxfile\read';  // 目录路径

        //获取目录下所有文件
        if ($handle = opendir($directory)) {
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != ".." && !strpos($file, '~')) {
                    $this->XLSXRead(filename: $directory, file: $file);
                }
            }
            closedir($handle);
        }

        dump(var: '转换成功！！！');
    }

    public function XLSXRead(string $filename, string $file): void {
        try {
            $spreadsheet = IOFactory::load($filename. '\\'. $file);
            $xlsx_array = $spreadsheet->getSheet(0)->toArray();

            // 获取本周开始时间
            $firstDayOfWeek = strtotime('monday this week');
            $startTime      = date('Y-m-d', $firstDayOfWeek);

            // 获取周五的时间
            $friday  = strtotime('friday this week');
            $endTime = date('Y-m-d', $friday);

            list($data, $names) = [[], []];
            unset($xlsx_array[0]);

            foreach ($xlsx_array as $index => $row) {
                if (in_array($row[1], $names)) {
                    $data[$row[1]]['H'][$row[8]][] = $row[10];
                } else {
                    $data[$row[1]]['A']            = $index;
                    $data[$row[1]]['B']            = $row[9];
                    $data[$row[1]]['C']            = $row[1];
                    $data[$row[1]]['D']            = '线上互动';
                    $data[$row[1]]['E']            = '辽宁';
                    $data[$row[1]]['F']            = 1;
                    $data[$row[1]]['G']            = $row[13];
                    $data[$row[1]]['H'][$row[8]][] = $row[10];
                    $data[$row[1]]['I']            = $startTime;
                    $data[$row[1]]['J']            = $endTime;
                    $names[]                       = $row[1];
                }
            }

            foreach ($data as &$datum) {
                $i = 1;
                $H = '';
                foreach ($datum['H'] as $index => $item) {
                    if ($i != 1) $H .= "\r";
                    $H .= $i.'.'.$index;

                    foreach ($item as $key => $value) {
                        $no = $key+1;
                        $H .= "\r  (".$no.".)".$value;
                    }
                    $datum['H'] = $H;
                    $i++;
                }
            }

            $this->save(data: $data, startTime: $startTime, endTime: $endTime, file: $file);
        } catch (\PhpOffice\PhpSpreadsheet\Exception $e) {
            echo '读取时报错：'.$e->getMessage();
        }
    }

    #[NoReturn] public function save(array $data, string $startTime, string $endTime, string $file): void {
        // 创建一个新的电子表格对象
        $spreadsheet = new Spreadsheet();

        // 选择默认工作表
        $sheet = $spreadsheet->getActiveSheet();

        try {
            // 设置单元格内容和样式
            $sheet->setCellValue('A1', '序号');
            $sheet->setCellValue('B1', '岗位');
            $sheet->setCellValue('C1', '人员');
            $sheet->setCellValue('D1', '项目归属');
            $sheet->setCellValue('E1', '归属');
            $sheet->setCellValue('F1', "项目参与度\r（0.1-1）");
            $sheet->setCellValue('G1', '备注');
            $sheet->setCellValue('H1', $startTime.'-'.$endTime);
            $sheet->setCellValue('H2', '工作事项');
            $sheet->setCellValue('I2', '开始日期');
            $sheet->setCellValue('J2', '预计交付日期');
            $sheet->setCellValue('K1', '');
            $sheet->setCellValue('K2', '工作事项');
            $sheet->setCellValue('L2', '开始日期');
            $sheet->setCellValue('M2', '预计交付日期');

            $num = 3;
            foreach ($data as $datum) {
                foreach ($datum as $k => $v) {
                    if ($k == 'H') {
                        $v = "\r".$v."\r";
                        $height = bcmul(bcadd(substr_count($v,"\r"),1),17);
                        $sheet->getRowDimension($num)->setRowHeight($height);
                    }
                    $v = $v?:'无';

                    // 设置单元格内容
                    $sheet->setCellValue($k.$num, $v);
                }

                $num++;
            }

            // 合并单元格
            $sheet->mergeCells('A1:A2');
            $sheet->mergeCells('B1:B2');
            $sheet->mergeCells('C1:C2');
            $sheet->mergeCells('D1:D2');
            $sheet->mergeCells('E1:E2');
            $sheet->mergeCells('F1:F2');
            $sheet->mergeCells('G1:G2');
            $sheet->mergeCells('H1:J1');
            $sheet->mergeCells('K1:M1');

            // 设置对齐方式为上下左右居中
            $alignment = new Alignment();
            $alignment->setHorizontal(Alignment::HORIZONTAL_CENTER);
            $alignment->setVertical(Alignment::VERTICAL_CENTER);

            // 设置边框样式
            $styleArray = [
                'borders' => [
                    'outline' => [
                        'borderStyle' => Border::BORDER_THIN,
                        'color'       => ['argb' => Color::BLACK->value],
                    ],
                ],
            ];

            $spreadsheet->getActiveSheet()->getStyle('F')->getAlignment()->setWrapText(true);
            $spreadsheet->getActiveSheet()->getStyle('H')->getAlignment()->setWrapText(true);

            // 设置背景颜色
            $fillType   = Fill::FILL_SOLID;
            $startColor = ['rgb' => Color::F1->value];
            $fill1 = compact('fillType', 'startColor');

            $startColor = ['rgb' => Color::F2->value];
            $fill2 = compact('fillType', 'startColor');

            $startColor = ['rgb' => Color::F0->value];
            $fill0 = compact('fillType', 'startColor');

            $sheet->getStyle('H1:H2')->getFill()->applyFromArray($fill0);
            $sheet->getStyle('I2')->getFill()->applyFromArray($fill0);
            $sheet->getStyle('J2')->getFill()->applyFromArray($fill0);
            $sheet->getStyle('K1:K2')->getFill()->applyFromArray($fill0);
            $sheet->getStyle('L2')->getFill()->applyFromArray($fill0);
            $sheet->getStyle('M2')->getFill()->applyFromArray($fill0);

            // 遍历所有单元格，并设置样式
            $maxColumn = $sheet->getHighestColumn();
            $maxRow    = $sheet->getHighestRow();
            for ($row = 1; $row <= $maxRow; $row++) {
                for ($col = 'A'; $col <= $maxColumn; $col++) {
                    $cell = $sheet->getCell($col . $row);

                    // 获取对齐方式 上方统一设置过
                    $cell->getStyle()->getAlignment()->setHorizontal($alignment->getHorizontal());
                    $cell->getStyle()->getAlignment()->setVertical($alignment->getVertical());
                    $cell->getStyle()->getFont()->setBold(true);

                    // 设置框线样式到所有单元格
                    $cell->getStyle()->applyFromArray($styleArray);

                    if ($row < 3) continue;
                    //轮番为行插入不同颜色
                    if ($row % 2 == 0) {
                        $cell->getStyle()->getFill()->applyFromArray($fill2);
                    } else {
                        $cell->getStyle()->getFill()->applyFromArray($fill1);
                    }

                    //不加粗展示
                    $cell->getStyle()->getFont()->setBold(false);
                }

                //设置行高
                if ($row < 3) $sheet->getRowDimension($row)->setRowHeight(15);
            }

            //遍历列
            for ($col = 'A'; $col <= $maxColumn; $col++) {
                // 设置列宽
                if ($col == 'F')  $sheet->getColumnDimension($col)->setWidth(13);
                elseif ($col < 'H') $sheet->getColumnDimension($col)->setWidth(9);
                elseif ($col == 'H' || $col == 'K') $sheet->getColumnDimension($col)->setWidth(62);
                else $sheet->getColumnDimension($col)->setWidth(15);
            }

            // 设置某列的单元格对齐方式为左对齐
            $alignment = $sheet->getStyle('H')->getAlignment();
            $alignment->setHorizontal(Alignment::HORIZONTAL_LEFT);

            // 获取单元格的样式对象，并设置H1为居中对齐方式
            $style = $sheet->getStyle('H1');
            $alignment = $style->getAlignment();
            $alignment->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

            // 计算并设置自适应列宽和行高
            $sheet->calculateColumnWidths();
            //        $sheet->calculateRowHeight();
            // 设置自动换行和行高
            $sheet->getStyle('A1:B2')->getAlignment()->setWrapText(true);
            $sheet->getRowDimension(1)->setRowHeight(-1); // 自动调整行高

            // 创建一个Xlsx写入器对象
            $writer = new Xlsx($spreadsheet);

            // 保存文件
            $writer->save('./save/'.$file);
        } catch (Exception $e) {
            echo "保存时报错：".$e->getMessage();
        }
    }

    public function get_week(): void {
        // 设置时区
        date_default_timezone_set('Asia/Shanghai');

        // 获取当前日期
        $currentDate = date('Y-m-d');

        // 获取当天是一周的星期几（0为星期日，1为星期一，以此类推）
        $dayOfWeek = date('w', strtotime($currentDate));

        // 计算本周的开始日期和结束日期
        $weekStartDate = date('Y-m-d', strtotime("-$dayOfWeek days", strtotime($currentDate)));
        $weekEndDate   = date('Y-m-d', strtotime("+" . (6 - $dayOfWeek) . " days", strtotime($currentDate)));

        // 输出结果
        echo "本周工作日开始日期：" . $weekStartDate . "\n";
        echo "本周工作日结束日期：" . $weekEndDate . "\n";
    }

//    public function dump($var, $echo = true, $label = null, $flags = ENT_SUBSTITUTE): string {
//        $label = (null === $label) ? '' : rtrim($label) . ':';
//
//        ob_start();
//        var_dump($var);
//        $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', ob_get_clean());
//
//        if (!extension_loaded('xdebug')) {
//            $output = htmlspecialchars($output, $flags);
//        }
//
//        $output = '<pre>' . $label . $output . '</pre>';
//
//        if ($echo) {
//            echo($output);
//        }
//
//        return $output;
//    }
}

function dump($var, $echo = true, $label = null, $flags = ENT_SUBSTITUTE): string {
    $label = (null === $label) ? '' : rtrim($label) . ':';

    ob_start();
    var_dump($var);
    $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', ob_get_clean());

    if (!extension_loaded('xdebug')) {
        $output = htmlspecialchars($output, $flags);
    }

    $output = '<pre>' . $label . $output . '</pre>';

    if ($echo) {
        echo($output);
    }

    return $output;
}